package com.atguigu.lease.common.config;

import lombok.Data;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;


import java.time.Duration;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableCaching
public class StgyRedisConfig {
    //springboot整合了redis启动器，启动时会初始化redisTemplate对象，
    // 在初始化它之前会先创建RedisConnectionFactory连接工厂
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory){
        //redis缓存配置
        RedisCacheConfiguration config = RedisCacheConfiguration
                .defaultCacheConfig() //使用默认配置
                .entryTtl(Duration.ofSeconds(3000L))//自动缓存的过期时间
                .serializeKeysWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new StringRedisSerializer())) //键的序列化器
                .serializeValuesWith(RedisSerializationContext.SerializationPair //值的序列化器
                        .fromSerializer(new GenericJackson2JsonRedisSerializer()))
//                .disableCachingNullValues() 禁用缓存空数据
                ;
        //创建缓存管理器对象：
        return RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
    }

}
